<?php

namespace App\Kuafu\Log\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\User\Service\UserService;

class OperateLogModel extends BaseModel
{
    use KfSoftDeletes, KfUid;

    protected $table = "operate_logs";

    protected $fillable = [
        'module',
        'business',
        'businessId',
        'userId',
        'userName',
        'logName',
        'logContent',
        'logId',
        'status',
        'isDeleted',
        'createdAt',
        'createdByUid',
        'updatedAt',
        'updatedByUid',
    ];

    const STATUS_OK   = 1; // 已完成
    const STATUS_WAIT = 0; // 待处理

    const MODULE_DISTRIBUTION = 'distribution'; // 店铺分销


    const BUSINESS_DISTRIBUTION_UPDATE_RATIO = 'distributionUpdateRatio'; // 店铺分销修改分佣比率

    public static function add(
        string $module,
        string $business,
        int $businessId,
        int $logId,
        string $logName,
        string $logContent,
        int $status,
        int $userId,
        string $userName = ''
    ) {
        if (!$userName) {
            $userName = UserService::getUserInfoByIds($userId, ['username'])[0]['username'] ?? '';
        }

        return self::query()->create([
            'module'     => $module,
            'business'   => $business,
            'businessId' => $businessId,
            'userId'     => $userId,
            'userName'   => $userName,
            'logId'      => $logId,
            'logName'    => $logName,
            'logContent' => $logContent,
            'status'     => $status,
        ]);
    }

    public static function getData(
        string $module,
        string $business,
        int $businessId,
        int $logId = 0,
        string $order = 'asc'
    ) {
        return self::query()
                   ->where('module', $module)
                   ->where('business', $business)
                   ->where('businessId', $businessId)
                   ->when($logId > 0, function ($query) use ($logId) {
                       $query->where('logId', $logId);
                   })
                   ->orderBy('createdAt', $order)
                   ->first();
    }
}
